<?php


namespace app\common\service\workflow;

use app\admin\model\Admin;
use app\common\library\Utils;
use app\common\model\Project;
use app\common\model\workflow\Node as NodeModel;
use app\common\model\workflow\NodeRecord;
use app\common\model\workflow\NodeScope;
use app\common\model\workflow\Template as TemplateModel;
use app\common\model\workflow\WorkFlow as WFModel;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Request;

class WFCreate
{
    protected $creator;

    public function __construct($creator)
    {
        $this->creator = $creator;
    }

    /**
     * 创建一个流程
     * @param $flow_type 流程类型
     * @param $content 流程内容
     */
    public function create_flow($flow_type, $content, $name, $extend = ""){
        Db::startTrans();
        try {
            $template = TemplateModel::with('nodes')->where('flow_type',$flow_type)->find()->toArray();
            if($template == null){
                throw new Exception('未找到流程模板信息!');
            }
            $wf_data = [
                "template_id" => $template['id'],
                "template_name" => $template['name'],
                "flow_no" => Utils::createNo('WF'),
                "extend" => $extend,
                "name" => $name,
                "flow_model" => $template['flow_model'],
                "flow_type" => $template['flow_type'],
                "content" => $content,
                "creator_id" => $this->creator['id'],
                "creator_name" => $this->creator['nickname'],
                "creator_dpt" => '',
                "creator_dptname" => '',
                "creator_time" => time(),
                "total_step" => $template['total_step']
            ];
            $wf_flow = WFModel::create($wf_data);
//            $model_name = ['Reimbursement', 'Payment', 'Advance'][$template['flow_model']];
//            $extend_model = new \ReflectionClass("app\\common\\model\\apply\\".$model_name);
//            $extend_model_class = $extend_model->newInstance();
//            $extend_data = $extend_model_class->where([
//                ['no', '=', $extend]
//            ])->find();
            $extend_data = $content;
            $project_data = Project::find($content['project_id']);
            foreach($template['nodes'] as $node){
                $node_scopes = $node['node_type'] == 3 ? [['scope_id'=>$this->creator['id'],'scope_name'=>$this->creator['nickname'],'scope_range'=>1]] : $node['scopes'];
                $temp = [
                    "flow_id" => $wf_flow->id,
                    "name" => $node['name'],
                    "step" => $node['step'],
                    "node_type" => $node['node_type'],
                    "audit_type" => $node['audit_type'],
                    "scopes" => json_encode($node_scopes)
                ];
                $node_data = NodeModel::create($temp);

                foreach ($node['scopes'] as $scope){
                    $scope_users = $this->get_scope_user($scope, $project_data, $extend_data);
                    foreach ($scope_users as $scope_user){
                        $temp = [
                            "flow_id" => $wf_flow->id,
                            "node_id" => $node_data->id,
                            "node_step" => $node['step'],
                            "node_type" => $node['node_type'],
                            "scope_id" => $scope_user['id'],
                            "scope_name" => $scope_user['name']
                        ];
                        NodeScope::create($temp);
                    }
                }
            }
            Db::commit();
            return $wf_flow->toArray();
        } catch (Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage().'【'.$e->getFile().'】'.$e->getLine());
        }
    }

    /**
     * 获取节点审核人
     * @param $templete_node
     * @param $extend_model
     * @return array
     */
    private function get_scope_user($scope, $project_data, $extend_data): array {
        $users = [];
        switch ($scope['scope_range']){
            case '1': // 人
                $users[] = ['id'=> $scope['scope_id'], 'name'=> $scope['scope_name']];
                break;
            case '2': // 部门
                break;
            case '3': // 角色
                // 根据角色 查询人员
                $role_users = Admin::alias('admin')->join('admin_group_access access','admin.id = access.uid')->where([
                    ['access.group_id', '=', $scope['scope_id']]
                ])->select()->toArray();
                $temp_users = [];
                foreach ($role_users as $v){
                    $temp_users[] = ['id' => $v['id'], 'name' => $v['nickname']];
                    if(in_array($v, $project_data['member_ids'])) $users[] = ['id' => $v['id'], 'name' => $v['nickname']];
                }
                if(count($users) == 0) $users = $temp_users;
                break;
        }
        return $users;
    }
}